package com.hs.jhzd.controller;

import com.hs.jhzd.entity.Content;
import com.hs.jhzd.repository.ContentRepository;
import com.hs.jhzd.utils.ImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Base64Utils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/content")
@Slf4j
public class ContentController {
  @Autowired
  private ContentRepository repository;


  @Value("${jsbh}")
  private String jsbh;

  /**
   * 信息发布主页面.
   *
   * @param model model
   * @param pageable 分页信息
   * @param jsbh 监所编号
   * @return 信息发布主页面
   */
  @RequestMapping("/admin/main")
  public String main(Model model, Pageable pageable, String jsbh, String typeName) {
    if (StringUtils.isBlank(jsbh) || StringUtils.equals(jsbh, "null")) {
      return "redirect:/content/admin/main?jsbh=" + this.jsbh;
    }
    Page<Content> contents =
        StringUtils.isBlank(typeName) ? repository.findByJsbhOrderByIdDesc(jsbh, pageable)
            : repository.findByJsbhAndTypeOrderByIdDesc(jsbh, typeName, pageable);
    model.addAttribute("contents", contents);
    model.addAttribute("jsbh", jsbh);
    model.addAttribute("typeName", typeName);
    return "content-list";
  }

  /**
   * 添加信息发布页面.
   *
   * @param model model
   * @return 添加信息发布页面
   */
  @RequestMapping("/admin/addPage")
  public String newAddPage(Model model, String jsbh) {
    if (StringUtils.isBlank(jsbh)) {
      jsbh = this.jsbh;
    }
    model.addAttribute("jsbh", jsbh);
    model.addAttribute("mode", "add");
    return "content-save";
  }

  @RequestMapping("/admin/editPage")
  public String newModifyPage(Model model, @RequestParam Long id, String jsbh) {
    if (StringUtils.isBlank(jsbh)) {
      jsbh = this.jsbh;
    }
    model.addAttribute("jsbh", jsbh);
    model.addAttribute("mode", "edit");
    model.addAttribute("id", id);
    return "content-save";
  }

  @RequestMapping("/delete")
  @ResponseBody
  public String delete(@RequestParam(required = true) Long id) {
    repository.deleteById(id);
    return "success";
  }

  @RequestMapping("/save")
  @ResponseBody
  public String save(@RequestBody Content content) {
    content.setContent(compressPict(content.getContent()));
    log.debug("content.getContent()={}" + content.getContent());
    content.setContent(content.getContent());
    repository.save(content);
    return "success";
  }

  @RequestMapping("/getByTypeCode")
  @ResponseBody
  public List<Content> getByTypeCode(@RequestParam(required = true) String jsbh,
      @RequestParam(required = true) int typeCode) {
    jsbh=this.jsbh;
    return repository.findByJsbhAndTypeCode(jsbh, typeCode);
  }

  @RequestMapping("/getByTypeName")
  @ResponseBody
  public List<Content> getByTypeName(@RequestParam(required = true) String jsbh,
      @RequestParam(required = true) String typeName) {
    return repository.findByJsbhAndType(jsbh, typeName);
  }

  @RequestMapping("/getById")
  @ResponseBody
  public Content getById(@RequestParam(required = true) Long id) {
    Optional<Content> content = repository.findById(id);
    return content.isPresent() ? content.get() : null;
  }

  @RequestMapping("/getNewContentByjsbh")
  @ResponseBody
  public Content getById(@RequestParam(required = true) String jsbh) {
    if(StringUtils.isBlank(jsbh)){
      jsbh=this.jsbh;
    }
    return repository.findTop1ByJsbhOrderByCreateTimeDesc(jsbh);
  }
  
  private String compressPict(String content) {
    Document doc = Jsoup.parse(content);
    List<String> originalImgs = new ArrayList<>();

    Elements imags = doc.getElementsByTag("img");
    if (imags == null || imags.isEmpty()) {
      return content;
    }
    for (Element img : imags) {
      String imgHref = img.attr("src");
      String[] imgHrefSplits = imgHref.split(",");
      if (imgHrefSplits != null && imgHrefSplits.length < 1) {
        continue;
      }
      originalImgs.add(imgHrefSplits[1]);
    }
    if (CollectionUtils.isEmpty(originalImgs)) {
      return content;
    }

    for (String o : originalImgs) {
      // try {
      byte[] old = Base64Utils.decodeFromString(o);
      String picType = ImageUtil.getPicType(old);
      if (!StringUtils.endsWith(picType, "other")) {
        byte[] compressPic = ImageUtil.compressPic(old, picType);
        if (compressPic == null || compressPic.length < 1) {
          continue;
        }
        String compressImg = Base64Utils.encodeToString(compressPic);
        if (StringUtils.isNotBlank(compressImg)) {
          content = content.replace(o, compressImg);
        }
      }
      // } catch (Exception e) {
      // log.error("图片压缩错误", e.getMessage());
      // }
    }

    return content;
  }
}
